/**
 * 详情界面全屏的Gallery
 */
package net.youpo.Market.UI.AppInfo;

import java.io.File;

import net.youpo.Market.R;
import net.youpo.Market.Net.HttpConnection;
import net.youpo.Market.Util.ConstantsTable;
import net.youpo.Market.Util.Tools;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.Gallery.LayoutParams;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

public class FullScreenPictureActivity extends Activity implements
		ViewSwitcher.ViewFactory {
	private final int LOADING_DONE = 0;

	private ImageSwitcher mSwitcher;
	private ProgressDialog mLoadingDialog;
	private String[] mImageArr;
	private String mAppId;
	private Drawable[] mDrawableArr;

	private int mPosition = 0;
	private GestureDetector mGestureDetector;

	private static final float HORIZONTAL_SCROLL_DISTANCE = 10f;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.fullscreen_gallery);
		mLoadingDialog = ProgressDialog.show(this, "", "正在加载. 请等待...", true);
		Intent intent = getIntent();
		mPosition = intent.getIntExtra(ConstantsTable.GALLERY_POSITION, 0);
		mImageArr = intent.getStringArrayExtra(ConstantsTable.KEY_PS);
		mAppId = intent.getStringExtra(ConstantsTable.KEY_APPID);

		mSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitch);
		mSwitcher.setFactory(this);

		setupOnTouchListeners(findViewById(R.id.rootview));
		initData();
	}

	/**
	 * 初始化数据
	 */
	private void initData() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				if (mImageArr != null) {
					int length = mImageArr.length;
					mDrawableArr = new Drawable[length];
					for (int n = 0; n < length; n++) {
						// Log.e("H3c", "nx:" + mImageArr[n]);
						// 1.从缓存中获取
						File file = new File(ConstantsTable.CACHE_PATH + "/"
								+ mAppId + "_IMAGE_" + n);
						Bitmap bmp = null;
						if (file.exists()) {// 如果有缓存文件
							bmp = Tools
									.getBitmapFromCache(ConstantsTable.CACHE_PATH
											+ "/" + mAppId + "_IMAGE_" + n);
						} else {// 没有缓存就从网络获取
							HttpConnection hc = new HttpConnection();
							bmp = hc.getNetworkBitmap(mImageArr[n]);
							Tools.saveBmpToSd(bmp, mAppId + "_IMAGE_" + n);// 保存至缓存
						}
						mDrawableArr[n] = new BitmapDrawable(bmp);
					}
				}
				mHandler.sendEmptyMessage(LOADING_DONE);
			}
		}).start();
	}

	private void setupOnTouchListeners(View rootView) {
		mGestureDetector = new GestureDetector(this, new MyGestureListener());

		OnTouchListener rootListener = new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				mGestureDetector.onTouchEvent(event);

				// We do not use the return value of
				// mGestureDetector.onTouchEvent because we will not receive
				// the "up" event if we return false for the "down" event.
				return true;
			}
		};

		rootView.setOnTouchListener(rootListener);
	}

	private class MyGestureListener extends
			GestureDetector.SimpleOnGestureListener {

		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			if (Math.abs(velocityY) <= Math.abs(velocityX)
					&& Math.abs(velocityX) > HORIZONTAL_SCROLL_DISTANCE) {
				//
				System.out.println(velocityX);
				if (velocityX > 0) {
					if (mPosition > 0) {
						mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(
								FullScreenPictureActivity.this,
								R.anim.slide_out_right));
						mSwitcher.setInAnimation(AnimationUtils.loadAnimation(
								FullScreenPictureActivity.this,
								R.anim.slide_in_left));
						mSwitcher.setImageDrawable(mDrawableArr[--mPosition]);

					}
				} else {
					if (mPosition < (mDrawableArr.length - 1)) {
						mSwitcher.setInAnimation(AnimationUtils.loadAnimation(
								FullScreenPictureActivity.this,
								R.anim.slide_in_right));
						mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(
								FullScreenPictureActivity.this,
								R.anim.slide_out_left));
						mSwitcher.setImageDrawable(mDrawableArr[++mPosition]);

					} else if (mPosition == (mDrawableArr.length - 1)) {
						Toast.makeText(FullScreenPictureActivity.this, "最后一张",
								0).show();
						return true;
					}
				}
			}

			return true;
		}

	}

	@Override
	public View makeView() {
		ImageView i = new ImageView(this);
		i.setBackgroundColor(0xFF000000);
		i.setScaleType(ImageView.ScaleType.FIT_XY);
		i.setLayoutParams(new ImageSwitcher.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		return i;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		recycle();
		dissmissProgressDialog();
	}

	private void dissmissProgressDialog() {
		if (mLoadingDialog != null && !isFinishing()
				&& mLoadingDialog.isShowing()) {
			mLoadingDialog.dismiss();
		}
	}

	private void recycle() {
		if (mDrawableArr != null) {
			int length = mDrawableArr.length;
			for (int n = 0; n < length; n++) {
				if (mDrawableArr[n] != null) {
					Bitmap bitmap = ((BitmapDrawable) mDrawableArr[n])
							.getBitmap();
					if(bitmap != null){
					    bitmap.recycle();
					    bitmap = null;
					}
				}
			}
		}
	}

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case LOADING_DONE:
				mSwitcher.setImageDrawable(mDrawableArr[mPosition]);
				dissmissProgressDialog();
				break;
			default:
			}

		}
	};
}
